﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace Crawler_Plus
{
    public partial class Form1 : Form
    {
        List<Page> pages = new List<Page>();
        Crawler Crawler = new Crawler();
        public Form1()
        {
            InitializeComponent();
            Crawler.Crawler_Download += CrawlerDownload;
            Crawler.Crawler_Stop += CrawlerStop;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            bindingSource1.Clear();
            Crawler.urls.Add(textBox1.Text, false);
            new Thread(Crawler.Crawl).Start();
            label1.Text = "Starting";

        }
        private void CrawlerStop(Crawler crawler) //爬虫结束时执行
        {
            Action action_stop = () => label1.Text = "爬虫结束，爬取结果如下所示";
            if (this.InvokeRequired)  //判断是否需要调用invoke进行控件更改

            {
                this.Invoke(action_stop);
            }
            else
            {
                action_stop();
            }
        }
        private void CrawlerDownload(Crawler crawler,int index,String URL,String result) //执行爬虫时执行
        {
            Page page = new Page(index, URL, result);
            Action action = () => { bindingSource1.Add(page); };
            if (this.InvokeRequired)
            {
                this.Invoke(action);
            }
            else
            {
                action();
            }

        }
    }
}
